package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 查询设备Service业务层处理
 * 
 * @author laoYe
 * @date 2025-10-28
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient ioTDAClient;
    @Autowired
    private RedisTemplate redisTemplate;

    public static final String ALL_PRODUCT_KEY = "iot:all_product";

    /**
     * 查询查询设备
     * 
     * @param id 查询设备主键
     * @return 查询设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询查询设备列表
     * 
     * @param device 查询设备
     * @return 查询设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增查询设备
     * 
     * @param device 查询设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改查询设备
     * 
     * @param device 查询设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除查询设备
     * 
     * @param ids 需要删除的查询设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除查询设备信息
     * 
     * @param id 查询设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     *
     * @return
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = ioTDAClient.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200){
            throw new BaseException("同步产品列表失败");
        }
        //储存到redis 中
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr( response.getProducts()));
    }

    /**
     * 获取所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis 中获取数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //如果数据为空则返回空集合
        if (StrUtil.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 新增IoT设备管理
     *
     * @param dto
     * @return 结果
     */
    @Transactional
    @Override
    public void add(DeviceDto dto) {
        // 设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName,dto.getDeviceName()).count();
        if (count > 0){
            throw new ServiceException("设备名称重复");
        }
        //设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId,dto.getNodeId()).count();
        if (count > 0){
            throw new ServiceException("设备标识重复");
        }
        //同一位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation,dto.getBindingLocation())
                .eq(Device::getProductKey,dto.productKey)
                .eq(Device::getLocationType,dto.getLocationType())
                .eq(Device::getPhysicalLocationType,dto.getPhysicalLocationType())
                .count();
        if (count > 0){
            throw new ServiceException("同一位置不能绑定相同产品");
        }

        //保存到数据库
        //生成设备id 生成规则为product_id + "_" + node_id拼接而成
        String iotId = dto.getProductKey() + "_" + dto.getNodeId();
        dto.setIotId(iotId);
        //生成密钥
        String secret = UUID.randomUUID().toString().replaceAll("_","").substring(0,16);
        if (secret.length() < 8 || secret.length() > 32) {
            throw new RuntimeException("生成的设备密钥长度不合法：" + secret.length());
        }
        //转成数据对象
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        //是否有门禁，默认0
        device.setHaveEntranceGuard(0);
        //保存到数据库
        save(device);

        //注册到IoT平台
        registerDevice(dto,secret);
    }

    /**
     * 向华为云注册设备
     * @param dto
     * @param secret
     */
    private void registerDevice(DeviceDto dto, String secret) {
        AddDeviceRequest request = new AddDeviceRequest();
        //设备本身的信息
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        //生成设备id 生成规则为product_id + "_" + node_id拼接而成
        body.withDeviceId(dto.getIotId());
        request.withBody(body);

        AuthInfo authInfo = new AuthInfo();
        //密钥
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);

        request.withBody(body);
        try {
            AddDeviceResponse response = ioTDAClient.addDevice(request);
            System.out.println("response.getDeviceId() = " + response.getDeviceId());
        } catch (Exception e){
            log.error("注册设备失败",e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)){
            throw new ServiceException("设备不存在");
        }

        //调用华为云物联网接口
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = ioTDAClient.showDevice(showDeviceRequest);
        } catch (Exception e) {
            log.info("查询设备详情失败",e.getMessage());
            throw new BaseException("查询设备详情失败");
        }

        //属性拷贝
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        if (activeTime != null){
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            localDateTime = localDateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            detailVo.setActiveTime(localDateTime);
        }
        return detailVo;
    }

    /**
     * 查询设备上报的最新的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest showDeviceShadowRequest = new ShowDeviceShadowRequest();
        showDeviceShadowRequest.setDeviceId(iotId);
        ShowDeviceShadowResponse response;
        try {
            response = ioTDAClient.showDeviceShadow(showDeviceShadowRequest);
        } catch (Exception e){
            log.info("查询设备详情失败",e.getMessage());
            throw new BaseException("查询设备详情失败");
        }

        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty( shadow)){
            return null;
        }

        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<DeviceShadowDataVo> list = new ArrayList<>();

        //处理时间
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(),"yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            DeviceShadowDataVo vo = new DeviceShadowDataVo();
            vo.setEventTime(eventTime);
            vo.setFunctionId(k);
            vo.setValue(String.valueOf(v));
            list.add(vo);
        });

        return list;
    }

    /**
     * 修改IoT设备管理
     *
     * @param dto
     */
    @Override
    public void update(DeviceDto dto) {
        //校验设备是否存在
        Device one = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, dto.getIotId()));
        if (ObjectUtil.isEmpty(one)){
            throw new ServiceException("设备不存在");
        }
        //先修改数据库里的信息
        Device device = BeanUtil.toBean(dto, Device.class);
        updateById(device);
        //判断是否修改成功
        if (!updateById(device)){
            throw new ServiceException("修改设备数据库失败");
        }
        //同步更新到IoT平台

    }
}
